import { getDictionaryList, getGXDivision } from "@/api/user";

const state = {
    paramDicts: null,
    cityDict:null,
}
const mutations = {
    SET_CITY_DICT: (state, dict) => {
        state.cityDict = { ...state.cityDict, ...dict };
    },
    SET_PARAM_DICT: (state, { paramsKey, dict }) => {
        state.paramDicts = { ...state.paramDicts, [paramsKey]: dict };
    },
}
const actions = {
    getCityDict({ commit }) {
        return new Promise((resolve, reject) => {
            getGXDivision().then(res => {
                if (res.code === 200) {
                    commit('SET_CITY_DICT', res.data);
                    resolve(res.data);
                } else {
                    resolve({});
                }
            }).catch(error => {
                reject(error);
            });
        });
    },

    // 根据参数获取字典数据并存储
    getDictByParams({ commit }, params) {
        return new Promise((resolve, reject) => {
            // 生成参数唯一标识键
            const paramsKey = JSON.stringify(params);

            getDictionaryList(params).then(res => {
                if (res.code === 200) {
                    // 将根据参数获取的字典数据存储到paramDicts中
                    commit('SET_PARAM_DICT', { paramsKey, dict: res.data });
                    resolve(res.data);
                } else {
                    resolve({});
                }
            }).catch(error => {
                reject(error);
            });
        });
    },
}
const getters = {
    cityDict: state => state.cityDict,
    getDictByParamsKey: (state) => (params) => {
        const paramsKey = JSON.stringify(params);
        return state.paramDicts[paramsKey] || {};
    },
}
export default {
    namespaced: true,
    actions,
    mutations,
    state,
    getters
}
